package com.tian.web;

import com.tian.po.UserPO;
import com.tian.po.UserQueryPO;
import com.tian.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@Controller
@RequestMapping("/user")
public class UserController {

    @Autowired
    private UserService userService;

    @RequestMapping("/getUser/{id}")
    public String getUser(@PathVariable("id") long id, Model model){
        UserPO user = userService.findById(id);
        model.addAttribute("user", user);
        return "user/userView";
    }

    @RequestMapping(value = "/list", method = RequestMethod.GET)
    public String list(@RequestParam(value = "name", required = false) String name, Model model){
        UserQueryPO query = new UserQueryPO();
        query.setName(name);
        List<UserPO> list = userService.getAll(query);
        model.addAttribute("list", list);
        return "user/userList";
    }

    @RequestMapping(value = "/toAdd", method = RequestMethod.GET)
    public String toAdd(Model model){
        return "user/userAdd";
    }

    @RequestMapping(value = "/add", method = RequestMethod.POST)
    public String add(@ModelAttribute UserPO user, Model model){
        userService.add(user);
        model.addAttribute("flag", "success");
        return "user/userAdd";
    }

    @RequestMapping("/delete/{id}")
    public String delete(@PathVariable("id") long id, Model model){
        userService.deleteById(id);
        return "redirect:/user/list";
    }
}
